<template>
  <div>
    <el-card shadow="hover" style="margin: 18px 18px 0">
      <el-form inline>
        <el-form-item style="margin-right: 30px">
          <el-input placeholder="用户名" v-model="USERName" />
        </el-form-item>
        <el-form-item style="margin-bottom: 35px">
          <el-button
            type="primary"
            size="small"
            icon="el-icon-search"
            @click="queryUserdataHandler"
            >查询</el-button
          >
          <el-button size="small" @click="resetUserdataHandler">清空</el-button>
        </el-form-item>
      </el-form>
      <el-button
        type="primary"
        size="small"
        @click="showAddUserdataDialogHandler()"
        >添加</el-button
      >
      <el-button
        type="danger"
        size="small"
        @click="allDeleteHandler"
        :disabled="!(checks.length > 0)"
        >批量删除</el-button
      >
      <el-table
        :data="userdata"
        stripe
        border
        style="margin-top: 15px"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection"> </el-table-column>
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column label="用户名" prop="username"></el-table-column>
        <el-table-column label="用户昵称" prop="nickName"></el-table-column>
        <el-table-column label="角色列表" prop="roleName"></el-table-column>
        <el-table-column label="创建时间" prop="gmtCreate"></el-table-column>
        <el-table-column label="更新时间" prop="gmtModified"></el-table-column>
        <el-table-column label="操作" fixed="right" width="200">
          <template v-slot="{ row }">
            <el-button
              type="info"
              size="mini"
              icon="el-icon-user-solid"
              title="分配角色"
              @click="ShowRoleDialogHandler(row)"
            ></el-button>
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              title="修改用户"
              @click="showAddUserdataDialogHandler(row)"
              style="margin-right: 10px"
            ></el-button>
            <el-popconfirm
              :title="'你确定要删除' + row.username + '吗'"
              @onConfirm="deleteUserdataHandler(row.id)"
            >
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                title="删除用户"
                slot="reference"
              ></el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :page-size="limit"
        :total="total"
        :current-page="page"
        :page-sizes="[5, 10, 15]"
        layout="prev,pager,next,jumper,->,sizes,total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      ></el-pagination>
    </el-card>
    <el-dialog
      :title="messageType + '用户'"
      :visible.sync="isShowAddUserdataDialog"
      top="0"
    >
      <el-form
        label-width="100px"
        :model="formData"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称">
          <el-input v-model="formData.nickName"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="isShowPassword">
          <el-input v-model="formData.password"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="isShowAddUserdataDialog = false">取消</el-button>
        <el-button type="primary" @click="addOrUpdateUserdataHandler"
          >确定</el-button
        >
      </template>
    </el-dialog>
    <el-dialog title="设置角色" :visible.sync="isShowRoleDialog" top="0">
      <el-form label-width="70px" :model="formData">
        <el-form-item label="用户名">
          <el-input v-model="formData.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="角色列表">
          <template>
            <el-checkbox
              :indeterminate="isIndeterminate"
              v-model="checkAll"
              @change="handleCheckAllChange"
              >全选</el-checkbox
            >
            <el-checkbox-group
              v-model="checkedRolesId"
              @change="handleCheckedRolesChange"
            >
              <el-checkbox
                v-for="role in roleOptions"
                :label="role.id"
                :key="role.id"
                >{{ role.roleName }}</el-checkbox
              >
            </el-checkbox-group>
          </template>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="isShowRoleDialog = false">取消</el-button>
        <el-button type="primary" @click="allocationRoleHandler"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  requestUserListByPage,
  requestSaveUserdata,
  requestUpdateUserdata,
  requestDeleteUserdata,
  requestAllDeleteUserdata,
  requestQueryUserdata,
  requestGetRole,
  resquestAllocationRole,
} from "@/api/acluser";
import { Message, MessageBox } from "element-ui";
import { title } from "@/settings";
export default {
  name: "User",
  data() {
    return {
      userdata: [],
      // 当前页数
      page: 1,
      // 每页显示条数
      limit: 5,
      // 总条数
      total: 0,
      isShowAddUserdataDialog: false,
      formData: {
        username: "",
        nickName: "",
        password: "",
        id: "",
      },
      formRef: "",
      isShowPassword: true,
      messageType: "",
      checks: [],
      idList: [],
      USERName: "",
      isShowRoleDialog: false,
      // 角色设置
      checkAll: false,
      checkedRolesId: [],
      roleOptions: [],
      isIndeterminate: true,
      rules: {
        username: [
          {
            required: true,
            message: "用户名必须输入",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "密码必须输入",
            trigger: "blur",
          },
        ],
      },
    };
  },
  mounted() {
    this.getUserdataList();
  },
  methods: {
    // 初始化用户管理数据
    async getUserdataList() {
      console.log(this);

      const { page, limit } = this;
      const result = await requestUserListByPage(page, limit);
      console.log(result);
      this.userdata = result.data.items;
      this.total = result.data.total;
    },
    // 当前页改变
    handleCurrentChange(v) {
      this.page = v;
      this.getUserdataList();
    },
    // 每页显示条数改变
    handleSizeChange(v) {
      this.limit = v;
      this.getUserdataList();
    },
    // 点击添加和修改按钮
    showAddUserdataDialogHandler(data) {
      this.isShowAddUserdataDialog = true;
      if (data) {
        this.messageType = "修改";
        this.isShowPassword = false;
        // const { username, nickName } = data;
        // this.formData = {
        //   username: username,
        //   nickName: nickName,
        // };
        this.formData = { ...data };
      } else {
        this.messageType = "添加";
        this.isShowPassword = true;
        this.formData = {
          username: "",
          nickName: "",
          password: "",
        };
      }
      this.$nextTick(() => {
        this.$refs["formRef"].clearValidate();
      });
    },
    // 添加确定提交用户数据
    async addOrUpdateUserdataHandler() {
      try {
        await this.$refs["formRef"].validate();
        this.isShowAddUserdataDialog = false;
        if (this.messageType == "添加") {
          await requestSaveUserdata(this.formData);
        } else {
          await requestUpdateUserdata(this.formData);
        }
        this.getUserdataList();
        Message.success(this.messageType + "成功");
        // console.log(this.formData);
      } catch (e) {
        Message.success(this.messageType + "失败");
      }
    },
    // 删除指定用户
    async deleteUserdataHandler(id) {
      console.log("111");

      try {
        // await MessageBox({
        //   title: "提示",
        //   message: "你确定要删除吗",
        // });
        await requestDeleteUserdata(id);
        this.getUserdataList();
        Message.success("删除成功");
      } catch (e) {
        Message.success("删除失败");
      }
    },
    // 拿到多选框选中的值
    handleSelectionChange(checks) {
      this.checks = checks;
      console.log(this.checks);
    },
    // 批量删除
    async allDeleteHandler() {
      try {
        await MessageBox({
          title: "提示",
          message: "你确定要删除吗",
        });

        this.idList = this.checks.map((item) => item.id);
        // console.log(this.checks);
        // console.log(this.idList);
        await requestAllDeleteUserdata(this.idList);
        this.getUserdataList();
        Message.success("删除成功");
      } catch (e) {
        Message.success("删除失败");
      }
    },
    // 根据用户名查询用户
    async queryUserdataHandler() {
      try {
        const res = this.userdata.filter((item) => {
          return item.username == this.USERName;
        });
        // console.log(res);
        const ids = res.map((item) => item.id);
        let userId = String(ids);
        // console.log(userId);
        const userInfo = await requestQueryUserdata(userId);
        // console.log(userInfo);

        this.userdata = [userInfo.data.item];
        console.log(this.userdata);
      } catch (e) {}
    },
    // 清空查询用户
    async resetUserdataHandler() {
      this.getUserdataList();
    },

    // 点击设置角色按钮,获取用户角色数据
    async ShowRoleDialogHandler(row) {
      try {
        this.isShowRoleDialog = true;
        this.formData = { ...row };
        this.formData.id = row.id;
        const result = await requestGetRole(row.id);
        this.roleOptions = result.data.allRolesList;
        console.log(result);
        this.checkedRolesId = result.data.assignRoles.map((item) => item.id);
        this.checkAll =
          result.data.allRolesList.length === result.data.assignRoles.length;
        this.isIndeterminate =
          result.data.assignRoles.length > 0 &&
          result.data.assignRoles.length < result.data.allRolesList.length;
      } catch (e) {}
    },

    handleCheckAllChange(val) {
      this.checkedRolesId = val ? this.roleOptions.map((item) => item.id) : [];
      this.isIndeterminate = false;
    },
    handleCheckedRolesChange() {
      this.checkAll = this.checkedRolesId.length === this.roleOptions.length;
      this.isIndeterminate =
        this.checkedRolesId.length > 0 &&
        this.checkedRolesId.length < this.roleOptions.length;
    },
    // 点击确定分配角色
    async allocationRoleHandler() {
      try {
        this.isShowRoleDialog = false;
        await resquestAllocationRole(
          this.formData.id,
          this.checkedRolesId.join(",")
        );
        Message.success("设置成功");
        this.getUserdataList();
      } catch (e) {
        console.log(e);

        Message.success("设置失败");
      }
    },
  },
};
</script>

<style scoped></style>
